package net.infamily.logic.impl;

import net.infamily.dao.UserDao;
import net.infamily.logic.ProfileLogic;
import net.infamily.logic.UserLogic;
import net.infamily.model.Profile;
import net.infamily.model.User;

import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

public class UserLogicImpl implements UserLogic {

	@Inject
	private UserDao userDao;

	@Inject
	private ProfileLogic profileLogic;
	
	@Override
	@Transactional
	public User login(String email, String password) {
		User user = userDao.getUserByEmail(email);
		if (user != null && user.getPassword().equals(password))
			return user;
		else
			return null;
	}

	
	@Override
	public boolean registerUser(String email, String password) {
		Profile emptyProfile = profileLogic.createEmptyProfile();
		
		boolean regSucceeded = true;	
		try {			
			if (!registerUser(email, password, emptyProfile))
				regSucceeded = false;
		} 
		catch (Throwable t) {
			regSucceeded = false;
		}
		
		if (regSucceeded) {
			return true;
		} else {
			profileLogic.deleteProfile(emptyProfile);
			return false;
		}
	}	
	
	@Override
	@Transactional
	public boolean registerUser(String email, String password, Profile profile) {		
		User databaseUser = userDao.getUserByEmail(email);
		if (databaseUser != null) {
			return false; 
		}
				
		User user = new User();
		user.setEmail(email);
		user.setPassword(password);
		user.setAdminFlag(false);
		user.setProfileId(profile.getId());
		userDao.persist(user);			
		return true;
	}
}
